# -*- coding: utf-8 -*-
u"""2017.6.3 装饰器，输出运行时间."""


def ticktock(begin=False, colored_print=True):
    u"""一个输出运行时间的装饰器."""
    from datetime import datetime
    try:
        from termcolor import cprint
    except ImportError:
        colored_print = False

    def __deco(func):
        u"""多加了这一层就是为了在这个装饰器中添加参数"""
        def wrapper(*args, **kwargs):
            u"""真正装饰了func的那一环."""
            start_time = datetime.now()
            # 如果指定了begin，那么就输出开始时间，另外指定一个是否输出颜色的选项
            if begin:
                msg = '程序 %s 开始于：%s' % (func.__name__, start_time)
                if colored_print:
                    cprint(msg, 'white', 'on_blue')
                else:
                    print(msg)

            function = func(*args, **kwargs)
            # 同上，颜色输出
            msg = '程序 %s 共耗时：%s' % (func.__name__, datetime.now() - start_time)
            if colored_print:
                cprint(msg, 'white', 'on_blue')
            else:
                print(msg)
            return function
        return wrapper
    return __deco
